/* eslint-disable no-undef */
'use strict';
$(window.document).ready(function () {
  const $favoriteModal = $('#favorite-modal').attr('tabindex', 1),
    $favoriteTags = $favoriteModal.find('.tags'),
    $tagsInput = $favoriteModal.find('#tags'),
    $briefInput = $favoriteModal.find('#brief'),
    $collectBtn = $('.collect_btn'),
    $cancelCollectBtn = $('.cancel_collect_btn'),
    $errorTags = $favoriteModal.find('.error'),
    $body = $('body'),
    data = {
      _csrf: window.csrf || '',
    }; // cache
  var access_token = window.access_token || '';
  $cancelCollectBtn.click(function () {
    data.topic_id = $(this).data('id');
    $.post('/collect/de_collect', data, function (data) {
      if (data.status === 'success') {
        $cancelCollectBtn.hide();
        window.Alert.show({title: '取消收藏成功'}, 1e3);
        setTimeout(() => {
          window.location.reload();
        }, 500);
      }
    }, 'json');
  });
  window.handleSearchFavoriteModalLabel = debounce(function (event) {
    event.stopPropagation();
    event.preventDefault();
    event.stopImmediatePropagation();
    if ((event.type === 'keyup' || event.type === 'reset') && access_token) {
      $.post('/api/v1/collect/listTags', {tag_name: event.target.value, access_token: access_token}, function ({data}) {
        const tagsHtml = [], selectTags = $tagsInput.val().trim().split(' ');
        if (data && data.length) {
          data.forEach(function (tag) {
            const isSelected = selectTags.includes(tag.name);
            tagsHtml.push(`<span class="${tag.topics_size ? 'size' : ''} ${isSelected ? 'selected' : ''}" size="${tag.topics_size || ''}">${tag.name}</span>`)
          });
          $favoriteTags.html(tagsHtml.join(''));
        } else {
          $favoriteTags.html('<div class="empty">没有符合条件的标签</div>');
        }
      });
    }
  }, 500);
  $collectBtn.click(function () {
    const isLogin = $('.j-islogin').val();
    if (!isLogin) {
      let redirect_url = window.location.href;
      if (redirect_url && redirect_url.includes('redirect_url=')) {
        redirect_url = redirect_url.replace(/.+redirect_url=/, '');
      }
      window.location.href = '/signin?redirect_url=' + encodeURIComponent(redirect_url);
      return;
    }
    data.topic_id = $(this).data('id');
    $.when($.get('/collect/listTagsOnTopic?topic_id=' + this.dataset.id), $.get('/collect/listTags')).done(function (topicResponse, tagResponse) {
      var topicResponse = topicResponse[0],
        tagResponse = tagResponse[0];
      if (topicResponse && topicResponse.status === 'success' && tagResponse && tagResponse.status === 'success') {
        let topicTags = topicResponse.data.tags,
          is_collected = topicResponse.data.is_collected,
          brief = topicResponse.data.brief || '',
          tags = tagResponse.data;

        const tagsHtml = tags.map(function (item) {
          const size = item.topics_size ? item.topics_size : '';
          return '<span class="' + (size ? 'size' : '') + '" size="' + size + '">' + item.name + ' </span>';
        }).join('');
        if (tagsHtml) {
          $favoriteTags.html(tagsHtml).show();
        } else {
          $favoriteTags.parent().hide();
        }
        if (is_collected) {
          $favoriteModal.find('.cancel-btn').show();
        } else {
          $favoriteModal.find('.cancel-btn').hide();
        }

        if (topicTags.length) {
          const tagsValue = topicTags.map(item => item.name).join(' ');
          $tagsInput.val(tagsValue);
          $tagsInput.trigger('input');
        }
        $briefInput.val(brief);
      } else {
        $favoriteTags.hide();
      }
    });
    // }
    showModal();
  });
  $favoriteModal.on('click', '.tags span', function (event) {
    const text = event.currentTarget.innerText.trim();
    const values = $tagsInput.val().trim().split(' ');
    $(this).toggleClass('selected');
    if (values.length && values.includes(text)) {
      const index = values.indexOf(text);
      values.splice(index, 1);
    } else {
      values.push(text);
      $errorTags.html('');
    }
    if (values.length) {
      $tagsInput.val(values.join(' ') + ' ');
    } else {
      $tagsInput.val('');
    }
    $tagsInput.focus();
  });
  $favoriteModal.on('input', '#tags', function (event) {
    const values = event.currentTarget.value.trim().toLowerCase().split(' ');
    $favoriteTags.children().each(function (index, tag) {
      const text = tag.innerText.trim().toLowerCase();
      if (values.includes(text)) {
        $(tag).addClass('selected');
      } else {
        $(tag).removeClass('selected');
      }
    });
    $errorTags.html('');
  });
  $favoriteModal.on('click', '.favorite-btn', function () {
    handleSubmit();
  });
  $favoriteModal.on('click', '.cancel-btn', function () {
    $.post('/collect/de_collect', {topic_id: data.topic_id}, function (data) {
      if (data.status === 'success') {
        $cancelCollectBtn.hide();
        hideModal();
        window.Alert.show({title: '取消收藏成功'}, 1000);
      }
    }, 'json');
  });

  function onEnter(event) {
    if (event.target.form && event.target.form.className === 'collect-tags-search') return;
    if (event.keyCode === 13) {
      handleSubmit();
    }
  }

  function handleSubmit() {
    data.collect_tags = $tagsInput.val().trim();
    data.brief = $briefInput.val().trim();
    $.post('/collect/collect', data, function (data) {
      if (data.status === 'success') {
        $cancelCollectBtn.show();
        hideModal();
        window.Alert.show({title: '收藏成功'}, 1000);
      }
    }, 'json');
  }

  $favoriteModal.on('click', '.close', function () {
    hideModal();
  });

  $favoriteModal.on('hidden', function () {
    $tagsInput.val('');
    $favoriteModal.off('keyup', onEnter);
  });


  function showModal() {
    $favoriteModal.modal('show');
    // 禁止 body 滚动
    $favoriteModal.on('keyup', onEnter);
    $body.css('overflow-y', 'hidden');
  }

  function hideModal() {
    $favoriteModal.modal('hide');
    $body.attr('style', '');
  }
});

// 处理toc目录, 必须等页面渲染完才能处理, 否则高度会有误差
$(window).load(function () {
  let ua = navigator.userAgent.toLocaleLowerCase();
  if (ua.includes('iphone') || ua.includes('ipad') || ua.includes('android')) {
    return;
  }
  let str = $('.markdown-text').first().html();
  if (!str) {
    return;
  }
  let hs = $('.markdown-text').first().find('h1, h2, h3, h4');
  if (hs.length == 0) return;


  function getTopLevel(str) {
    if (str.includes('<h1')) {
      return 0;
    }
    if (str.includes('<h2')) {
      return 1;
    }
    if (str.includes('<h3')) {
      return 2;
    }
    if (str.includes('<h4')) {
      return 3;
    }
  }

  let topLevel = getTopLevel(str);


  let listBuilder = '';
  listBuilder += "<ul class=\"article-toc\">";
  for (let i = 0; i < hs.length; i++) {
    let ele = hs[i];
    let tagName = ele.tagName.toLowerCase();
    tagName = tagName[0] + (+tagName[1] - topLevel);
    let text = ele.innerText.replace(/<[^>]+>/g, '');
    let id = `toc_${i}`;
    $(ele).addClass('toc-title').attr("id", id);
    listBuilder += `<li class='toc-${tagName}'><a class="toc-link-#${i}" href="#${id}">${text}</a></li>`;
  }
  listBuilder += "</ul>";

  const result = listBuilder;
  if (!result) return;
  $('#toc_box').html(result);
  $('.toc_panel').show();
  const panel_zuozhe_height = document.getElementById('sidebar').children[0].offsetHeight + 80;

  const listHeight = getTitleHeight();
  // 获取目录所有的a标签
  const aList = Array.prototype.slice.apply($(".article-toc a"));

  // 获取文章每个标题到顶部的距离
  function getTitleHeight() {
    const listHeight = [];

    const titleList = Array.prototype.slice.call($('.markdown-text').first().children('.toc-title'));
    titleList.forEach((item, index) => {
      listHeight.push(item.offsetTop);
    });

    // 滚动的距离无法取到最后一个，因此在数组最后加上上一个的两倍达到效果
    listHeight.push(2 * (titleList[titleList.length - 1].offsetTop));

    return listHeight;
  }


  document.addEventListener('scroll', (e) => {
    let scrollY = window.pageYOffset;
    if (scrollY > panel_zuozhe_height) {
      $('.toc_panel').css('position', 'fixed');
    } else {
      $('.toc_panel').css('position', 'static');
    }

    scrollY = scrollY - 60;

    for (let i = 0; i < listHeight.length - 1; i++) {
      let h1 = listHeight[i];
      let h2 = listHeight[i + 1];
      if (scrollY >= h1 && scrollY <= h2) {
        const data = document.getElementsByClassName(`toc-link-#${i}`)[0];
        aList.forEach(list => {
          if (data == list) {
            // 根据文章滚动百分比计算目录滚动高度
            // document.getElementById('toc_box').scrollTop = (scrollY / document.body.offsetHeight) * document.getElementById('toc_box').scrollHeight;
            list.classList.add('active');
          } else {
            list.classList.remove('active');
          }
        });
      }
    }
  });
});



